﻿
using HappyDog.Services;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace HappyDog.BgServices
{
    public class WatchDog : BackgroundService
    {
        private IConfiguration config;

        public WatchDog([FromServices] IConfiguration config)
        {
            this.config = config;
        }
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            return Task.Factory.StartNew(async () =>
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    await Task.Delay(5000);
                    var dogs=config.GetSection("dogs");
                    Logger.logger.Info("------------------------------------------------------------");
                    foreach(var dog in dogs.GetChildren())
                    {
                        try
                        {
                            var now = DateTime.Now;
                            var dog_name = dog.GetValue<string>("dog_name");
                            var food_file_path = dog.GetValue<string>("food_file_path");
                            var hunger_endurance_second = dog.GetValue<int>("hunger_endurance_second");
                            var hunger_count = dog.GetValue<string>("hunger_count");
                            var script_after_die = dog.GetSection("script_after_die");
                            var script_command = script_after_die.GetValue<string>("command");
                            var script_arguments = script_after_die.GetValue<string>("arguments");
                            var script_verb = script_after_die.GetValue<string>("verb");
                            var script_workdir = script_after_die.GetValue<string>("script_workdir");
                            if (script_verb == null)
                            {
                                script_verb = "";
                            }
                            TempStore.Instance.lasthungertime.SetDicValue(dog_name, now.ToString("yyyy-MM-dd HH:mm:ss"));

                            FileInfo fi = new FileInfo(food_file_path);
                            if (fi.Exists)
                            {
                                var lasttime = fi.LastWriteTime;
                                TempStore.Instance.lastsendingtime.SetDicValue(dog_name, lasttime.ToString("yyyy-MM-dd HH:mm:ss"));
                                var ts = now - lasttime;
                                if (ts > TimeSpan.FromSeconds(hunger_endurance_second))
                                {
                                    Logger.logger.Warn(dog_name+":正在执行投食呼叫脚本，因为其已经超过最大不投食时间：" + ts.ToString());
                                    ProcessStartInfo psi = new ProcessStartInfo()
                                    {
                                        WorkingDirectory=script_workdir,
                                        FileName = script_command, // 使用 PowerShell 运行脚本
                                        Arguments = script_arguments, // 指定脚本路径和参数
                                        UseShellExecute = true, // 必须为 true 才能使用管理员权限
                                        Verb = script_verb, // 以管理员身份运行
                                        CreateNoWindow = true // 隐藏窗口（可选）
                                    };

                                    try
                                    {
                                        // 启动进程
                                        Process.Start(psi);
                                        TempStore.Instance.lastcrytime.SetDicValue(dog_name, now.ToString("yyyy-MM-dd HH:mm:ss"));
                                    }
                                    catch (Exception ex)
                                    {
                                        Logger.logger.Error(ex,$"执行脚本异常: {dog_name}");
                                    }
                                }
                                else
                                {
                                    var tts = TimeSpan.FromSeconds(hunger_endurance_second) - ts;
                                    Logger.logger.Info(dog_name+":非饥饿状态，上次投食：" + lasttime.ToString()+ "。还能坚持："+ tts.ToString());
                                    TempStore.Instance.lasteattime.SetDicValue(dog_name, now.ToString("yyyy-MM-dd HH:mm:ss"));
                                }
                            }
                            else
                            {
                                Logger.logger.Info(dog_name+":食物文件不存在，暂不监控,"+food_file_path);
                            }

                        }catch(Exception ex)
                        {
                            Logger.logger.Error(ex,"喂狗时出现异常");
                        }

                    }
                    Logger.logger.Info("------------------------------------------------------------");
                }
            });
        }
    }
}
